package com.fingard.dsp.bank.directbank.boc01;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IForeignCurrency;
import com.fingard.dsp.bank.reqrespobj.foreigncurrsingle.ReqForeignCurrSingle;
import com.fingard.dsp.bank.reqrespobj.foreigncurrsingle.ReqQryForeignCurrSingle;
import com.fingard.dsp.bank.reqrespobj.foreigncurrsingle.RetAtsForeignCurrSingle;
import com.fingard.dsp.bank.reqrespobj.foreigncurrsingle.detail.RetAtsForeignCurrPayDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/10/30.
 */
public class BOC01ForeignCurrSinglePay extends BOC01Base implements IForeignCurrency {
    @Override
    public RetAtsForeignCurrSingle foreignCurrPay(ReqForeignCurrSingle reqForeignCurrSingle) throws Exception {
        RetAtsForeignCurrSingle retAts = new RetAtsForeignCurrSingle(reqForeignCurrSingle.reqHeader);
        RetAtsForeignCurrPayDetail tmpRetDetail = null;
        if("DomesticFCP".equals(reqForeignCurrSingle.reqHeader.transType)){//境内汇款
                tmpRetDetail = b2e0062(reqForeignCurrSingle);
        }else if("CrossborderFCP".equals(reqForeignCurrSingle.reqHeader.transType)){//跨境汇款
                tmpRetDetail = b2e0200(reqForeignCurrSingle);
        }else if("OutsideFCP".equals(reqForeignCurrSingle.reqHeader.transType)){//全球汇款
            if(this.getBankConfig().getValueAsBool("isUseNewPay")){//是否使用b2e0041接口
                tmpRetDetail = d_1908_b2e0041(reqForeignCurrSingle);
            }else{
                tmpRetDetail = b2e0200(reqForeignCurrSingle);
            }
        }else {
             tmpRetDetail = new RetAtsForeignCurrPayDetail();
            tmpRetDetail.respCode ="-1";
            tmpRetDetail.respInfo = "未知的业务类型："+reqForeignCurrSingle.reqHeader.transType;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    //d_1908_b2e0041 全球转汇
    private RetAtsForeignCurrPayDetail d_1908_b2e0041(ReqForeignCurrSingle reqForeignCurrSingle) throws Exception {
        RetAtsForeignCurrPayDetail retDetail = new RetAtsForeignCurrPayDetail();
        BOC01Header bankHeader = new BOC01Header();
        bankHeader.trncod = "b2e0041";//交易代码
        bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        //Date tmpDateNow = new Date();
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("trn-" + bankHeader.trncod + "-rq");
        xmlWriter.writeElementClosed("ceitinfo");
        if (StringHelper.hasAnyChar(getBankConfig().getValueAsString("b2e0041transtype"))) {
            xmlWriter.writeElementString("transtype", getBankConfig().getValueAsString("b2e0041transtype"));
        } else {
            xmlWriter.writeElementClosed("transtype");
        }

        XElement tmpXElement = new XElement(bankHeader.trncod + "-rq", "");
        tmpXElement.addChild(new XElement("insid", reqForeignCurrSingle.singleDetail.askNumber));
        if (reqForeignCurrSingle.singleDetail.sameBnk.equals("1")) {
            tmpXElement.addChild(new XElement("cltype", "1"));//清算方式 1,3
        } else {
            tmpXElement.addChild(new XElement("cltype", "3"));//清算方式 1,3
        }

        XElement fractnXElement = new XElement("fractn", "");
        fractnXElement.addChild(new XElement("fribkn", reqForeignCurrSingle.singleDetail.payArea));
        fractnXElement.addChild(new XElement("actacn", reqForeignCurrSingle.singleDetail.payAct));
        fractnXElement.addChild(new XElement("curcde", this.convertCurToBank(reqForeignCurrSingle.singleDetail.payCur)));
        tmpXElement.addChild(fractnXElement);

        XElement toactnXElement = new XElement("toactn", "");
        if (reqForeignCurrSingle.singleDetail.sameBnk.equals("1")) {
            toactnXElement.addChild(new XElement("toibkn", reqForeignCurrSingle.singleDetail.recArea));
        } else {
            toactnXElement.addChild(new XElement("toibkn", reqForeignCurrSingle.singleDetail.recSwiftCode));
        }
        toactnXElement.addChild(new XElement("toactacn", reqForeignCurrSingle.singleDetail.recAct));
        toactnXElement.addChild(new XElement("toacctype", ""));
        toactnXElement.addChild(new XElement("toname", reqForeignCurrSingle.singleDetail.recName));
        toactnXElement.addChild(new XElement("tobknm", reqForeignCurrSingle.singleDetail.getOppBankLocation()));
        toactnXElement.addChild(new XElement("toaddr", getBankConfig().getValueAsString("defaultAddr")));
        tmpXElement.addChild(toactnXElement);

        tmpXElement.addChild(new XElement("trnamt", AmountNotO(reqForeignCurrSingle.singleDetail.payAmount)));
        tmpXElement.addChild(new XElement("trncur", this.convertCurToBank(reqForeignCurrSingle.singleDetail.payCur)));
        tmpXElement.addChild(new XElement("amtype", "3"));//金额类型 1:交易金额 2:收款金额；3:付款金额
        tmpXElement.addChild(new XElement("payeechnnam", "3"));
        if (reqForeignCurrSingle.singleDetail.sameBnk.equals("1")) {
            tmpXElement.addChild(new XElement("payeechnnam", reqForeignCurrSingle.singleDetail.recName));
        } else {
            tmpXElement.addChild(new XElement("payeechnnam", ""));
        }
        tmpXElement.addChild(new XElement("payeeidtype", ""));
        if (reqForeignCurrSingle.singleDetail.sameBnk.equals("1")) {
            tmpXElement.addChild(new XElement("payeeidnum", reqForeignCurrSingle.singleDetail.certNum));
        } else {
            tmpXElement.addChild(new XElement("payeeidnum", ""));
        }
        tmpXElement.addChild(new XElement("payeephone", reqForeignCurrSingle.singleDetail.cellPhone));
        if (reqForeignCurrSingle.singleDetail.paySpd.equals("1")) {
            tmpXElement.addChild(new XElement("cuspriolv", "1"));
            tmpXElement.addChild(new XElement("priolv", "1"));
        } else {
            tmpXElement.addChild(new XElement("cuspriolv", "0"));
            tmpXElement.addChild(new XElement("priolv", "0"));
        }
        tmpXElement.addChild(new XElement("furinfo", reqForeignCurrSingle.singleDetail.purpose));
        tmpXElement.addChild(new XElement("trfdate", Format.Date8Format.format(reqForeignCurrSingle.singleDetail.getPayDateTime())));
        tmpXElement.addChild(new XElement("feemode", reqForeignCurrSingle.singleDetail.costMode));//手续费支出方
        tmpXElement.addChild(new XElement("exchangeto", ""));
        tmpXElement.addChild(new XElement("remittanceuse", reqForeignCurrSingle.singleDetail.purpose));
        tmpXElement.addChild(new XElement("paymentdetails", reqForeignCurrSingle.singleDetail.memo));
        tmpXElement.addChild(new XElement("businesstype", ""));
        if (StringHelper.hasAnyChar(reqForeignCurrSingle.singleDetail.recSwiftCode)) {
            if (reqForeignCurrSingle.singleDetail.recSwiftCode.length() == 8) {
                String agencyswiftcode = String.format("%X11S", reqForeignCurrSingle.singleDetail.recSwiftCode);
                tmpXElement.addChild(new XElement("agencyswiftcode", agencyswiftcode));
            } else {
                tmpXElement.addChild(new XElement("agencyswiftcode", reqForeignCurrSingle.singleDetail.recSwiftCode));
            }

        } else {
            tmpXElement.addChild(new XElement("agencyswiftcode", ""));
        }
        //xmlWriter.writeElementClosed("trftime");

        if (reqForeignCurrSingle.singleDetail.sameBnk.equals("1")) {
            tmpXElement.addChild(new XElement("bocflag", "1"));
        } else {
            tmpXElement.addChild(new XElement("bocflag", "0"));
        }

        //nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
        xmlWriter.writeXElement(tmpXElement);
        //XElement tmpXElement = new XElement("DCOPDPAYX","");
        //tmpXElement.addChild(new XElement("YURREF",p_req1908.singleDetail.askNumber));
        //xmlWriter.writeXElement(tmpXElement);

        xmlWriter.writeEndDocument();//写入报文完成
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspcod");
                String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspmsg");
                if (isActiveRetCode(tmprspcod)) {
                    //retDetail.respCode = "0";
                    //retDetail.respInfo = tmpRetMsg;
                    //retDetail.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                    retDetail.respCode = "0";
                    retDetail.transState = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/" + bankHeader.trncod + "-rs/status/rspcod");
                    retDetail.payInfoCode = retDetail.transState;
                    retDetail.respInfo = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/" + bankHeader.trncod + "-rs/status/rspmsg");
                    retDetail.reqSeqID = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/" + bankHeader.trncod + "-rs/insid");
                    String filename = getBankConfig().getValueAsString("saveDir") + File.separator + Format.Date8Format.format(new Date())
                            + File.separator + reqForeignCurrSingle.singleDetail.askNumber + ".txt";
                    String obssid = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/" + bankHeader.trncod + "-rs/obssid");
                    FileHelper.writeFile(filename, retDetail.reqSeqID + "|" + obssid + "|" + bankHeader.trncod, "gbk");
                } else {
                    retDetail.respCode = "-1";
                    retDetail.transState = tmprspcod;
                    if (StringHelper.isNullOrEmpty(tmprspmsg)) {
                        tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2eerror-rs/status/rspmsg");
                    }
                    retDetail.respInfo = tmprspmsg;
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = reqForeignCurrSingle.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    //1944 全球转汇支付结果查询
    public RetAtsForeignCurrPayDetail d_1944_b2e0042(ReqQryForeignCurrSingle reqQryForeignCurrSingle) throws Exception {
        //返回ATS的对象
        RetAtsForeignCurrPayDetail retDetail = new RetAtsForeignCurrPayDetail();
        BOC01Header bankHeader = new BOC01Header();
        bankHeader.trncod = "b2e0042";//交易代码

        bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, bankHeader);//写入通用的头部节点
        xmlWriter.writeStartElement("trn-" + bankHeader.trncod + "-rq");
        xmlWriter.writeStartElement(bankHeader.trncod + "-rq");
        xmlWriter.writeElementString("ibknum", "");//查询账户的海外机构号或联行号
        xmlWriter.writeElementString("actacn", reqQryForeignCurrSingle.reqHeader.ownAct);
        xmlWriter.writeStartElement("datescope");
        xmlWriter.writeElementString("from", Format.Date8Format.format(Format.DateTimeFormat.parse(reqQryForeignCurrSingle.reqHeader.payDateTime)));
        xmlWriter.writeElementString("to", Format.Date8Format.format(Format.DateTimeFormat.parse(reqQryForeignCurrSingle.reqHeader.payDateTime)));
        xmlWriter.writeEndElement();
        xmlWriter.writeElementString("remtyp", "0");
        xmlWriter.writeElementString("prdtyp", "B");
        xmlWriter.writeElementString("chltyp", "0");
        xmlWriter.writeEndDocument();

        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspcod");
                    String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspmsg");
                    if (isActiveRetCode(tmprspcod)) {
                        //retDetail.respCode = "0";
                        //retDetail.respInfo = tmpRetMsg;
                        //retDetail.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                        while (tmpBkReader.read("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/" + bankHeader.trncod + "-rs")) {
                            if (tmpBkReader.readedXElement.getSingleText("insid").equals(reqQryForeignCurrSingle.askNumber)) {
                                String tmpRetCode = tmpBkReader.readedXElement.getSingleText("status/rspcod");
                                String tmpRetInfo = tmpBkReader.readedXElement.getSingleText("status/rspmsg");
                                retDetail.respCode = "0";
                                retDetail.transState = tmpRetCode;
                                retDetail.payInfoCode = retDetail.transState;
                                retDetail.respInfo = tmpRetInfo;
                                retDetail.reqSeqID = tmpBkReader.readedXElement.getSingleText("insid");
                            }
                        }
                    } else {
                        retDetail.respCode = "-1";
                        if (StringHelper.isNullOrEmpty(tmprspmsg)) {
                            tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2eerror-rs/status/rspmsg");
                        }
                        retDetail.respInfo = tmprspmsg;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        return retDetail;
    }


    private RetAtsForeignCurrPayDetail b2e0200(ReqForeignCurrSingle reqForeignCurrSingle) {
        RetAtsForeignCurrPayDetail detail = new RetAtsForeignCurrPayDetail();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            BOC01Header header = new BOC01Header();
            header.trnid =getQryTransID();
            header.trncod ="b2e0200";
            writeCommonHeader(xmlTextWriter,header);
            xmlTextWriter.writeStartElement("trn-b2e0200-rq");
            xmlTextWriter.writeElementString("TRANS_TYPE","");//交易类型
            xmlTextWriter.writeStartElement("b2e0200-rq");
            xmlTextWriter.writeElementString("OBSS_ID","");//网银交易流水号

            xmlTextWriter.writeElementString("AUTH_EXPIRY_DT",Format.Date10Format.format(new Date()));//授权有效日期
            xmlTextWriter.writeElementString("REM_MODE","S");//汇款类型
            xmlTextWriter.writeElementString("RET_LVL","1".equals(reqForeignCurrSingle.singleDetail.paySpd)?"2":"1");//发电等级
            xmlTextWriter.writeElementString("TRN_AMT",reqForeignCurrSingle.singleDetail.payAmount);// 汇款金额
            xmlTextWriter.writeElementString("TRN_CUR",convertCurToBank(reqForeignCurrSingle.singleDetail.payCur));//汇款币种
            xmlTextWriter.writeElementString("CEX_AMT",AmountNotO(reqForeignCurrSingle.singleDetail.payCashAmount));//现汇金额
            xmlTextWriter.writeElementString("CEX_ACNO",reqForeignCurrSingle.singleDetail.payCashAct);//现汇帐号
            xmlTextWriter.writeElementString("PUR_AMT", AmountNotO(reqForeignCurrSingle.singleDetail.payPurchaseAmt));//购汇金额
            xmlTextWriter.writeElementString("PUR_ACNO",reqForeignCurrSingle.singleDetail.payPurchaseAct);//购汇帐号
            xmlTextWriter.writeElementString("OTR_AMT", AmountNotO(reqForeignCurrSingle.singleDetail.payOtherAmount));// 其它金额
            xmlTextWriter.writeElementString("OTR_ACNO",reqForeignCurrSingle.singleDetail.payOtherAct);//其它帐号
            xmlTextWriter.writeElementString("FEE_ACNO",reqForeignCurrSingle.singleDetail.feeAct);//付费账号

            xmlTextWriter.writeElementString("FRN_NAME_50A",getEnglishByCN(reqForeignCurrSingle.singleDetail.payName));//汇款人姓名
            xmlTextWriter.writeElementString("FRN_ADDRESS_50A",getEnglishByCN(reqForeignCurrSingle.singleDetail.payAddr));//汇款人地址
            xmlTextWriter.writeElementString("ORG_CDE",bankFront.corpNo);//组织机构代码
            xmlTextWriter.writeElementString("BEDL_NAME_56A",reqForeignCurrSingle.singleDetail.recAgentBnkName);//收款银 行之代理行名称
            xmlTextWriter.writeElementString("BEDL_ADDRESS_56A","");//收款银 行之代理行地址
            xmlTextWriter.writeElementString("BDL_ACT_57A",reqForeignCurrSingle.singleDetail.recAgentBnkAct);//收款人开 户银行在其代理行账号
            xmlTextWriter.writeElementString("BEAK_NAME",reqForeignCurrSingle.singleDetail.recCNAPSName);//收款银行 名称
            xmlTextWriter.writeElementString("BEAK_ADDRESS","");//收款银行 地址
            String recIBAN=reqForeignCurrSingle.singleDetail.recIBAN;
            if(StringHelper.hasAnyChar(recIBAN)){
                xmlTextWriter.writeElementString("TO_ACT_ACN_59A",recIBAN);//收款人IBAN帐号
            }else {
                xmlTextWriter.writeElementString("TO_ACT_ACN_59A",reqForeignCurrSingle.singleDetail.recAct);//收款人帐号
            }
            xmlTextWriter.writeElementString("TO_NAME_59A",getEnglishByCN(reqForeignCurrSingle.singleDetail.recName));//收款人姓名
            xmlTextWriter.writeElementString("TO_ADDRESS_59A",getEnglishByCN(reqForeignCurrSingle.singleDetail.recAddr));//收款人地址
            xmlTextWriter.writeElementString("POSTSCRIPTMT",reqForeignCurrSingle.singleDetail.purpose);//汇款附言
            xmlTextWriter.writeElementString("FEE_MODE",reqForeignCurrSingle.singleDetail.costMode);//国内外费 用承担
            xmlTextWriter.writeElementString("COU_CDE",reqForeignCurrSingle.singleDetail.recCountryCode);//收款人常驻国 家(地区)代码
            if("A".equals(reqForeignCurrSingle.singleDetail.payMethod)) {
                xmlTextWriter.writeElementString("PAY_TYPE","1" );//付款方式
            }else if("P".equals(reqForeignCurrSingle.singleDetail.payMethod)) {
                xmlTextWriter.writeElementString("PAY_TYPE", "2");//付款方式
            }else if("R".equals(reqForeignCurrSingle.singleDetail.payMethod)) {
                xmlTextWriter.writeElementString("PAY_TYPE", "3");//付款方式
            }else if("O".equals(reqForeignCurrSingle.singleDetail.payMethod)) {
                xmlTextWriter.writeElementString("PAY_TYPE", "4");//付款方式
            }
            if(StringHelper.hasAnyChar(reqForeignCurrSingle.singleDetail.transCode1)) {
                xmlTextWriter.writeElementString("TRN_CD1", reqForeignCurrSingle.singleDetail.transCode1);//交易编码1
                xmlTextWriter.writeElementString("TRN_CUR1", convertCurToBank(reqForeignCurrSingle.singleDetail.currency1));//交易币别1
                xmlTextWriter.writeElementString("TRN_AMT1", AmountNotO(reqForeignCurrSingle.singleDetail.amout1));//交易金额1
                xmlTextWriter.writeElementString("TRN_RE1", reqForeignCurrSingle.singleDetail.postScript1);//交易附言1
            }else{
                xmlTextWriter.writeElementString("TRN_CD1", "");//交易编码1
                xmlTextWriter.writeElementString("TRN_CUR1", "");//交易币别1
                xmlTextWriter.writeElementString("TRN_AMT1", "");//交易金额1
                xmlTextWriter.writeElementString("TRN_RE1", "");//交易附言1
            }
            if(StringHelper.hasAnyChar(reqForeignCurrSingle.singleDetail.transCode1)) {
                xmlTextWriter.writeElementString("TRN_CD2", reqForeignCurrSingle.singleDetail.transCode2);//交易编码2
                xmlTextWriter.writeElementString("TRN_CUR2", convertCurToBank(reqForeignCurrSingle.singleDetail.currency2));//交易币别2
                xmlTextWriter.writeElementString("TRN_AMT2", AmountNotO(reqForeignCurrSingle.singleDetail.amout2));//交易金额2
                xmlTextWriter.writeElementString("TRN_RE2", reqForeignCurrSingle.singleDetail.postScript2);//交易附言2
            }else{
                xmlTextWriter.writeElementString("TRN_CD2", "");//交易编码2
                xmlTextWriter.writeElementString("TRN_CUR2", "");//交易币别2
                xmlTextWriter.writeElementString("TRN_AMT2", "");//交易金额2
                xmlTextWriter.writeElementString("TRN_RE2", "");//交易附言2
            }
            xmlTextWriter.writeElementString("IS_BGD_PAY",reqForeignCurrSingle.singleDetail.isBondedGood);//本币款项是否 为保税货物项 下付款
            xmlTextWriter.writeElementString("COM_NUM",reqForeignCurrSingle.singleDetail.contractNo);//合同号
            xmlTextWriter.writeElementString("INV_NUM",reqForeignCurrSingle.singleDetail.invoiceNo);//发票号

            xmlTextWriter.writeElementString("WHB_NUM",reqForeignCurrSingle.singleDetail.businessNum);//外汇局批件/备案表号/业 务编号
            xmlTextWriter.writeElementString("PER_NAME",reqForeignCurrSingle.singleDetail.contactPerson);//申请人姓名
            xmlTextWriter.writeElementString("PER_TEL",reqForeignCurrSingle.singleDetail.contactNum);//申请人联系电 话
            xmlTextWriter.writeElementString("ERP_REF","");//集团业务编号
            xmlTextWriter.writeElementString("REM_TYP","1");//汇款种类
            xmlTextWriter.writeElementString("FEE_PAY_TYPE","3");//费用交付方式
            xmlTextWriter.writeElementString("IBK_NUM","");//联行号
            xmlTextWriter.writeElementString("CUS_FLAG","TC");//客户标识
            xmlTextWriter.writeElementString("REMARK1","");//备注1
            xmlTextWriter.writeElementString("REMARK2","");//备注2
            xmlTextWriter.writeElementString("BED_BIC_57A",reqForeignCurrSingle.singleDetail.recSWIFTCODE);//收款银行
            xmlTextWriter.writeElementString("TRF_DATE","");//转账日期
            xmlTextWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0200-rs/status/rspcod");
                    String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0200-rs/status/rspmsg");
                    if (isActiveRetCode(tmprspcod)) {
                        if (tmpBkReader.read("/bocb2e/trans/trn-b2e0200-rs/b2e0200-rs")) {
                            detail.respCode = "0";
                            detail.transState = tmpBkReader.readedXElement.getSingleText("status/rspcod");
                            detail.payInfoCode = detail.transState;
                            detail.respInfo = tmpBkReader.readedXElement.getSingleText("status/rspmsg");
                            detail.reqSeqID = reqForeignCurrSingle.singleDetail.askNumber;
                            String insid = tmpBkReader.readedXElement.getSingleText("insid");
                            String obssid = tmpBkReader.readedXElement.getSingleText("OBSS_ID");
                            String filename = getBankConfig().getValueAsString("saveDir")+ File.separator+Format.Date8Format.format(new Date())
                                    +File.separator+reqForeignCurrSingle.singleDetail.askNumber+".txt";
                            FileHelper.writeFile(filename,insid+"|"+obssid+"|"+header.trncod,"gbk");
                        } else {
                            detail.respCode = "0";
                            detail.transState = tmprspcod;
                            detail.payInfoCode = tmprspcod;
                            detail.respInfo = tmprspmsg;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmprspmsg;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = tmpStrRet[1];
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = tmpStrRet[0];
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpStrRet[1];
            }
        }catch (Exception ex){
            ex.printStackTrace();
            detail.respCode  ="-1";
            detail.respInfo = ex.getMessage();
        }
        return detail;
    }

    /**
     * 金额为0转换为“”
     * @param money
     * @return
     */
    private String AmountNotO(String money) {
        BigDecimal bigDecimal=new BigDecimal(money);
        if(bigDecimal.compareTo(new BigDecimal("0"))==0) {
            money = "";
        }
        return money;
    }

    //境内外币付款
    private RetAtsForeignCurrPayDetail b2e0062(ReqForeignCurrSingle reqForeignCurrSingle){
        RetAtsForeignCurrPayDetail detail = new RetAtsForeignCurrPayDetail();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            BOC01Header header = new BOC01Header();
            header.trncod = "b2e0062";
            header.trnid = getQryTransID();
            writeCommonHeader(xmlTextWriter, header);
            xmlTextWriter.writeStartElement("trn-b2e0062-rq");
            xmlTextWriter.writeElementClosed("ceitinfo");//数字签名
            String transtype = getBankConfig().getValueAsString("transtype");
            xmlTextWriter.writeElementString("transtype",transtype,true);//交易类型
            xmlTextWriter.writeStartElement("b2e0062-rq");
            xmlTextWriter.writeElementString("insid",header.trnid);
            xmlTextWriter.writeElementString("obssid","");//网银交易流水号
            xmlTextWriter.writeStartElement("fractn");
            xmlTextWriter.writeElementString("trfdate", Format.Date8Format.format(new Date()));//转账日期
            xmlTextWriter.writeElementString("trntyp","T");//汇款方式
            xmlTextWriter.writeElementString("trnamt",reqForeignCurrSingle.singleDetail.payAmount);//汇款金额
            xmlTextWriter.writeElementString("trncur",convertCurToBank(reqForeignCurrSingle.singleDetail.payCur));//汇款货币
            xmlTextWriter.writeElementString("fribkn",getBankConfig().getMapValueByKey("caps",reqForeignCurrSingle.singleDetail.payCNAPSCode));//联行号
            xmlTextWriter.writeElementString("cexact",reqForeignCurrSingle.singleDetail.payCashAct);//现汇账户
            xmlTextWriter.writeElementString("cexamt",AmountNotO(reqForeignCurrSingle.singleDetail.payCashAmount));//现汇金额
            xmlTextWriter.writeElementString("puract",reqForeignCurrSingle.singleDetail.payPurchaseAct);//购汇账户
            xmlTextWriter.writeElementString("puramt",AmountNotO(reqForeignCurrSingle.singleDetail.payPurchaseAmt));//购汇金额
            xmlTextWriter.writeElementString("othact",reqForeignCurrSingle.singleDetail.payOtherAct);//其他账户
            xmlTextWriter.writeElementString("othamt",AmountNotO(reqForeignCurrSingle.singleDetail.payOtherAmount));//其他金额
            xmlTextWriter.writeElementString("feeact",reqForeignCurrSingle.singleDetail.feeAct);//付费账户
            xmlTextWriter.writeElementString("frname",getEnglishByCN(reqForeignCurrSingle.singleDetail.payName));//汇款人名称
            xmlTextWriter.writeElementString("fraddr",getEnglishByCN(reqForeignCurrSingle.singleDetail.payAddr));//汇款人地址
            xmlTextWriter.writeElementString("orgcde",bankFront.corpNo);//组织机构代码
            xmlTextWriter.writeEndElement();
            xmlTextWriter.writeStartElement("toactn");
            xmlTextWriter.writeElementString("bedtyp",reqForeignCurrSingle.singleDetail.sameBnk);//收款行类型
            if("1".equals(reqForeignCurrSingle.singleDetail.sameBnk)) {
                /*xmlTextWriter.writeElementString("toibkn",
                        getBankConfig().getMapValueByKey("caps",reqForeignCurrSingle.singleDetail.recSWIFTCODE));//收款行联行号*/
                xmlTextWriter.writeElementString("toibkn",reqForeignCurrSingle.singleDetail.recAreaCode);
            }else{
                xmlTextWriter.writeElementClosed("toibkn");
            }
            xmlTextWriter.writeElementString("bedlnm",reqForeignCurrSingle.singleDetail.recAgentBnkName);//收款银行之代理行名称
            xmlTextWriter.writeElementClosed("bedadr");//收款银行之代理行地址
            xmlTextWriter.writeElementString("beaknm",reqForeignCurrSingle.singleDetail.recCNAPSName);//收款人开户银行名称
            xmlTextWriter.writeElementString("beaadr",reqForeignCurrSingle.singleDetail.recAreaName);//收款人开户银行地址
            xmlTextWriter.writeElementClosed("bdlact");//收款人开户银行在其代 理行账号
            xmlTextWriter.writeElementString("toname",getEnglishByCN(reqForeignCurrSingle.singleDetail.recName));//收款人名称
            xmlTextWriter.writeElementString("toaddr",getEnglishByCN(reqForeignCurrSingle.singleDetail.recAddr));//收款人地址
            xmlTextWriter.writeElementString("actacn",reqForeignCurrSingle.singleDetail.recAct);//收款账号
            xmlTextWriter.writeEndElement();
            xmlTextWriter.writeElementString("furinfo",reqForeignCurrSingle.singleDetail.purpose);//汇款附言
            xmlTextWriter.writeElementString("feemode",reqForeignCurrSingle.singleDetail.costMode);//中间费用方式
            xmlTextWriter.writeElementString("coucde","156");//收款人常驻 国家（或地 区）代码
            xmlTextWriter.writeElementString("paytyp",reqForeignCurrSingle.singleDetail.payMethod);//付款方式
            xmlTextWriter.writeElementString("priolv","1".equals(reqForeignCurrSingle.singleDetail.paySpd)?"U":"N");//发电等级
            xmlTextWriter.writeElementString("canflg","1".equals(reqForeignCurrSingle.singleDetail.isBondedGood)?"Y":"N");//是否为报税货物项下付款
            String rettyp = getBankConfig().getMapValueByKey("rettypMap", reqForeignCurrSingle.singleDetail.payProperty);
            if (StringHelper.isNullOrEmpty(rettyp)) {
                rettyp = "";
            }
            xmlTextWriter.writeElementString("rettyp", rettyp);//付汇性质
            xmlTextWriter.writeElementString("lstdat","");//最迟装运日期
            xmlTextWriter.writeElementString("trncd1",reqForeignCurrSingle.singleDetail.transCode1);//交易编码1
            xmlTextWriter.writeElementString("trnam1",AmountNotO(reqForeignCurrSingle.singleDetail.amout1));//相应金额1
            xmlTextWriter.writeElementString("trncd2",reqForeignCurrSingle.singleDetail.transCode2);//交易编码2
            xmlTextWriter.writeElementString("trnam2",AmountNotO(reqForeignCurrSingle.singleDetail.amout2));//相应金额2
            xmlTextWriter.writeElementString("comnum",reqForeignCurrSingle.singleDetail.contractNo);//合同号
            xmlTextWriter.writeElementString("invnum",reqForeignCurrSingle.singleDetail.invoiceNo);//发票号
            xmlTextWriter.writeElementString("whbnum",reqForeignCurrSingle.singleDetail.businessNum);//外汇局批件号/备案表号/业务编号
            xmlTextWriter.writeElementString("comcde","");//报关单经营 单位代码
            xmlTextWriter.writeElementString("pernam",reqForeignCurrSingle.singleDetail.contactPerson);//申请人姓名
            xmlTextWriter.writeElementString("pertel",reqForeignCurrSingle.singleDetail.contactNum);//联系电话
            xmlTextWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0062-rs/status/rspcod");
                    String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0062-rs/status/rspmsg");
                    if (isActiveRetCode(tmprspcod)) {
                        if (tmpBkReader.read("/bocb2e/trans/trn-b2e0062-rs/b2e0062-rs")) {
                            detail.respCode = "0";
                            detail.transState =tmpBkReader.readedXElement.getSingleText("status/rspcod");
                            detail.payInfoCode = detail.transState;
                            detail.respInfo = tmpBkReader.readedXElement.getSingleText("status/rspmsg");
                            detail.reqSeqID = reqForeignCurrSingle.singleDetail.askNumber;
                            String insid = tmpBkReader.readedXElement.getSingleText("insid");
                            String obssid = tmpBkReader.readedXElement.getSingleText("obssid");
                            String filename = getBankConfig().getValueAsString("saveDir")+ File.separator+Format.Date8Format.format(new Date())
                                    +File.separator+reqForeignCurrSingle.singleDetail.askNumber+".txt";
                            FileHelper.writeFile(filename,insid+"|"+obssid+"|"+header.trncod,"gbk");
                        } else {
                            detail.respCode = "0";
                            detail.transState = tmprspcod;
                            detail.payInfoCode = tmprspcod;
                            detail.respInfo = tmprspmsg;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmprspmsg;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = tmpStrRet[1];
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = tmpStrRet[0];
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpStrRet[1];
            }
        }catch (Exception ex){
            ex.printStackTrace();
            detail.respCode  ="-1";
            detail.respInfo = ex.getMessage();
        }
        return detail;
    }

    @Override
    public RetAtsForeignCurrSingle qryForeignCurrPay(ReqQryForeignCurrSingle reqQryForeignCurrSingle) throws Exception {
        RetAtsForeignCurrSingle retAts = new RetAtsForeignCurrSingle(reqQryForeignCurrSingle.reqHeader);
        RetAtsForeignCurrPayDetail tmpRetDetail = null;
        String filename = getBankConfig().getValueAsString("saveDir")+ File.separator+reqQryForeignCurrSingle.bgnDate.substring(0,10).replaceAll("-","")
                +File.separator+reqQryForeignCurrSingle.askNumber+".txt";
        try {
            if (!FileHelper.existFile(filename)) {
                throw new Exception("不存在,请和银行确认该交易!");
            }
            //insid|obssid|交易码
            String context = FileHelper.readFileText(filename, "gbk");
            String[] reqIds = context.split("\\|");
            if (reqIds.length == 3) {
                if ("b2e0200".equals(reqIds[2])) {
                    tmpRetDetail = b2e0204(reqQryForeignCurrSingle,reqIds);
                } else if ("b2e0062".equals(reqIds[2])) {
                    tmpRetDetail = b2e0007(reqQryForeignCurrSingle,reqIds);
                }else if("b2e0041".equals(reqIds[2])){
                    tmpRetDetail = d_1944_b2e0042(reqQryForeignCurrSingle);
                }
            }else{
                throw new Exception("存放银行的流水号文件内容异常");
            }
        }catch (Exception ex){
            tmpRetDetail = new RetAtsForeignCurrPayDetail();
            tmpRetDetail.respCode ="-1";
            tmpRetDetail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }



    private RetAtsForeignCurrPayDetail b2e0007(ReqQryForeignCurrSingle reqQryForeignCurrSingle,String[] reqIds) {
        RetAtsForeignCurrPayDetail detail = new RetAtsForeignCurrPayDetail();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            BOC01Header header = new BOC01Header();
            header.trncod = "b2e0007";
            header.trnid = getQryTransID();
            writeCommonHeader(xmlTextWriter, header);
            xmlTextWriter.writeStartElement("trn-b2e0007-rq");
            xmlTextWriter.writeStartElement("b2e0007-rq");
            xmlTextWriter.writeElementString("insid",reqIds[0]);
            xmlTextWriter.writeElementString("obssid",reqIds[1]);
            xmlTextWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0007-rs/status/rspcod");
                    String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0007-rs/status/rspmsg");
                    if (isActiveRetCode(tmprspcod)) {
                        //retDetail.respCode = "0";
                        //retDetail.respInfo = tmpRetMsg;
                        //retDetail.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                        if (tmpBkReader.read("/bocb2e/trans/trn-b2e0007-rs/b2e0007-rs")) {
                            detail.respCode = "0";
                            detail.transState =tmpBkReader.readedXElement.getSingleText("status/rspcod");
                            detail.payInfoCode = detail.transState;
                            detail.respInfo = tmpBkReader.readedXElement.getSingleText("status/rspmsg");
                        } else {
                            detail.respCode = "0";
                            detail.transState = tmprspcod;
                            detail.payInfoCode = tmprspcod;
                            detail.respInfo = tmprspmsg;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmprspmsg;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = tmpStrRet[1];
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = tmpStrRet[0];
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpStrRet[1];
            }
            return detail;
        }catch (Exception ex){
            ex.printStackTrace();
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
        }
        return detail;
    }

    private RetAtsForeignCurrPayDetail b2e0204(ReqQryForeignCurrSingle reqQryForeignCurrSingle,String[] reqIds) {
        RetAtsForeignCurrPayDetail detail = new RetAtsForeignCurrPayDetail();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            BOC01Header header = new BOC01Header();
            header.trncod ="b2e0204";
            header.trnid = getQryTransID();
            writeCommonHeader(xmlTextWriter,header);
            xmlTextWriter.writeStartElement("trn-b2e0204-rq");
            xmlTextWriter.writeStartElement("b2e0204-rq");
            xmlTextWriter.writeElementString("ERP_REF","");
            xmlTextWriter.writeElementString("OBSS_ID",reqIds[1]);
            xmlTextWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0204-rs/status/rspcod");
                    String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0204-rs/status/rspmsg");
                    if (isActiveRetCode(tmprspcod)) {
                        if (tmpBkReader.read("/bocb2e/trans/trn-b2e0204-rs/b2e0204-rs")) {
                            String tmpRetCode = tmpBkReader.readedXElement.getSingleText("status/rspcod");
                            String tmpRetInfo = tmpBkReader.readedXElement.getSingleText("status/rspmsg");
                            detail.respCode = "0";
                            String FAIL_REASON = tmpBkReader.readedXElement.getSingleText("FAIL_REASON");
                            String FAIL_DESCRPT = tmpBkReader.readedXElement.getSingleText("FAIL_DESCRPT");
                            String APPLY_STATE = tmpBkReader.readedXElement.getSingleText("APPLY_STATE");//申请状态 申请状态(长度为2位；0-申请成功；1-申请失败;2-处理中)
                            if (FAIL_DESCRPT.length() > 0) {
                                detail.payInfoCode = "FAIL_REASON+" + FAIL_REASON + "+" + FAIL_DESCRPT;
                            } else if (FAIL_REASON.length() > 0) {
                                detail.payInfoCode = "FAIL_REASON+" + FAIL_REASON;
                            } else {
                                detail.payInfoCode = tmpRetCode;
                            }
                            detail.transState = tmpRetCode + "+APPLY_STATE+" + APPLY_STATE;
                            detail.respInfo = tmpBkReader.readedXElement.getSingleText("FAIL_DESCRPT");
                            if (StringHelper.isNullOrEmpty(detail.respInfo)) {
                                detail.respInfo = tmpRetInfo;
                            }
                            detail.reqSeqID = reqIds[1];
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = tmprspmsg;
                            detail.reqSeqID = reqIds[1];
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmprspmsg;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = tmpStrRet[1];
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = tmpStrRet[0];
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpStrRet[1];
            }
            return detail;
        }catch (Exception ex){
            ex.printStackTrace();
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
        }
        return detail;
    }
}
